<template>
<!--<div class="root" v-html="html">-->

<!--</div>-->
    <div>
        <div style="position: fixed;left: 20px;">
           <el-menu
                background-color="#00004f"
                text-color="#ffffff">
               <el-menu-item  @click="save">保存为PDF</el-menu-item>
               <el-menu-item @click="showImageDialog">图片设置</el-menu-item>
               <el-menu-item @click="showFontDialog">字体设置</el-menu-item>
           </el-menu>
        </div>
        <div class="root" id="printContainer" :style="{backgroundColor:rootStyle.backgroundColor}">
            <div>
            <div v-for="segment in story.segments">
                <div v-for="paragraph in story.paragraphs.slice(segment.startParagraph,segment.endParagraph+1)">
                    <div v-if="paragraph.match('第.*[章节]')!==null">
                        <h1 :style="{fontSize:titleStyle.fontSize+'pt', color:titleStyle.fontColor}">{{paragraph}}</h1>
                    </div>
                    <div v-else>
                        <p :style="{fontSize:fontStyle.fontSize +'pt', color:fontStyle.fontColor}">{{paragraph}}</p>
                    </div>
                </div>
                <div class="line">
                    <div v-for="img in segment.imgs">
                        <img :src="img.url" class="image"/>
                    </div>
                </div>
            </div>
            </div>
        </div>
    </div>
    <el-drawer
        v-model="dialogVisible.font"
        direction="rtl"
        title="字体设置"
    >
        <div>
            <el-form label-width="120px">
                <el-form-item label="正文字体大小">
                    <el-input-number v-model="fontStyle.fontSize"></el-input-number>
                </el-form-item>
                <el-form-item label="正文字体颜色">
                    <el-color-picker v-model="fontStyle.fontColor"></el-color-picker>
                </el-form-item>
                <el-form-item label="标题字体大小">
                    <el-input-number v-model="titleStyle.fontSize"></el-input-number>
                </el-form-item>
                <el-form-item label="标题字体颜色">
                    <el-color-picker v-model="titleStyle.fontColor"></el-color-picker>
                </el-form-item>
                <el-form-item label="背景颜色">
                    <el-color-picker v-model="rootStyle.backgroundColor"></el-color-picker>
                </el-form-item>
            </el-form>
        </div>
    </el-drawer>
    <el-drawer
        v-model="dialogVisible.image"
        direction="rtl"
        title="图片设置">
        <div v-for="segment in story.segments" style="margin-bottom: 10px">
           <el-row style="margin-bottom: 10px">
               <el-col :span="4">段落</el-col>
               <el-col :span="20">{{segment.startParagraph}}-{{segment.endParagraph}}</el-col>
           </el-row>
            <el-row style="margin-bottom: 10px">
               <el-col :span="4">画面描述</el-col>
               <el-col :span="20"><el-input maxlength="50" v-model="segment.summary"/></el-col>
           </el-row>
            <el-row style="margin-bottom: 10px">
               <el-scrollbar >
                   <div style="width: 200%">
                       <el-upload
                           style="height: 100%; overflow: auto;scrollbar-width: thin;"
                           v-model:file-list="segment.imgs"
                           list-type="picture-card">

                       </el-upload>
                   </div>
               </el-scrollbar>
           </el-row>
            <el-row style="margin-bottom: 10px">
                <div style="width: 100%">
                    <el-button type="primary" @click="reload(segment)" style="position:relative;left: 450px">重新生成</el-button>
                </div>
            </el-row>
        </div>
    </el-drawer>
</template>

<script setup lang="ts">
import {reactive, ref} from "vue";
import {storyStore} from "@/pinia/story";
import {Story,StorySegment} from "@/utils/story";
import chatglmapi from "@/utils/chatglmapi";
import {wukongapi} from "@/utils/wukongapi";
//页面导出pdf
import downloadPDF from '@/utils/htmlToPdf'
import { ElLoading, ElMessage} from "element-plus";
const store = storyStore();
let story = store.getStory;
let threadCount = 4
let fontStyle = reactive({
    fontSize: 16,
    fontColor: "#0000ff",
})
let titleStyle = reactive({
    fontSize: 24,
    fontColor: "#0000ff",
})
let rootStyle = reactive({
    backgroundColor: "#000000",
})
let dialogVisible= reactive({
    font:false,
    image:false
})
const reload=(segment)=>{
    wukongapi({style: "", desc: segment.summary.substring(0,50)}).then(data=>{
        let imgs = data.data.pictures
        for(let img in imgs){
            segment.imgs.push({
                name:`${segment.startParagraph}-${segment.endParagraph}-${segment.summary}`,
                url:imgs[img]
            })
        }
    })

}
const showFontDialog = ()=>{
    dialogVisible.font = true
}
const showImageDialog = ()=>{
    dialogVisible.image = true
}

const save = ()=>{
    const loading = ElLoading.service({
        lock: true,
        text: 'Loading',
        background: 'rgba(0, 0, 0, 0.7)',
    })
    new Promise((resolve, reject) =>{
        downloadPDF(document.getElementById("printContainer"),"1.pdf",(err, tot, cur)=>{
            if(err){
                loading.close()
                ElMessage({
                    showClose: true,
                    message: err,
                    type: 'error',
                })
            }else if(tot === cur){
                loading.close()
                ElMessage({
                    showClose: true,
                    message: "下载成功",
                    type: 'success',
                })
            }
        })
    }).then(()=>{
        loading.close()
    }).catch(()=>{
        loading.close()
    })
}

async function render(){
    const summaryTaskTot = story.segments.length
    const generateTaskTot = story.segments.length
    const summaryTask = []
    const generateTask = []
    let count = 0
    for(let i=0;i<story.segments.length;i++){
        let segment = story.segments[i]
        if(segment.summary === undefined || segment.summary===null || segment.summary === ""){
            let history = [
                {
                    "content": "接下来我将会给你一段文章，请你用30个字以内描述文章中的画面",
                    "role": "user"
                },
                {
                    "content": "请提供文章，我会尽力为您描述画面。",
                    "role": "bot"
                },
                {
                    "content": segment.text,
                    "role": "user"
                }
            ]
            summaryTask.push({
                history,
                segment
            })

            let summary = ""
            let timer = setInterval(()=>{
                if(count>=threadCount){
                    console.log("waiting...")
                    return
                }else{
                    count++;
                    chatglmapi(history,async(e,history)=>{
                        if(e.event==="add"){
                            summary+=e.data
                        }else if(e.event === "finish"){
                            summary = "科幻 "+summary
                            story.segments[i].summary = summary.substring(0,50)
                            let data = await wukongapi({style: "", desc:summary.substring(0,50)})
                            let imgs = data.data.pictures
                            for(let img in imgs){
                                story.segments[i].imgs.push({
                                    name:`${segment.startParagraph}-${segment.endParagraph}-${segment.summary}`,
                                    url:imgs[img]
                                })
                            }
                            count--;
                            console.log("summary",summary)
                            console.log(imgs)
                        }else if(e.event === "error"){
                            console.log("error");
                            count --;
                        }else if(e.event === "interrupted"){
                            console.log("interrupted");
                        }
                    },true)
                    clearInterval(timer)
                }

            },2000)
        }
    }
}
render()
</script>

<style scoped>
.root{
    width: 60%;
    margin: 20px auto;
    padding: 10px;
    background: rgba(80, 88, 43, 0.5);
}
p:before{
    content: "";
    display: inline-block;
    width: 2em;
}
.line{
    display: flex;
    flex-direction: row;
    justify-content: center;
}
.image{
    width: 256px;
    height: 256px;
}
h1{
    text-align: center;
}
</style>
